package com.ecommerce.order.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 用户上下文过滤器
 * 将网关传递的用户信息从请求头中提取并设置为请求属性
 */
@Component
@Slf4j
public class UserContextFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
            throws IOException, ServletException {
        
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        // 从请求头中获取用户信息（网关传递）
        String userId = httpRequest.getHeader("X-User-ID");  // 网关使用 X-User-ID
        String username = httpRequest.getHeader("X-User-Name");
        String role = httpRequest.getHeader("X-User-Role");
        
        // 如果网关头信息不存在，尝试从前端直接发送的头信息获取
        if (userId == null) {
            userId = httpRequest.getHeader("X-User-Id");  // 前端可能使用 X-User-Id
        }
        
        log.debug("UserContextFilter - 从请求头获取用户信息: userId={}, username={}, role={}", userId, username, role);
        
        // 将用户信息设置为请求属性，供控制器使用
        if (userId != null) {
            httpRequest.setAttribute("userId", userId);
            log.debug("设置请求属性 userId: {}", userId);
        }
        
        if (username != null) {
            httpRequest.setAttribute("username", username);
            log.debug("设置请求属性 username: {}", username);
        }
        
        if (role != null) {
            httpRequest.setAttribute("role", role);
            log.debug("设置请求属性 role: {}", role);
        }
        
        // 记录请求信息
        log.info("请求 {} {} - 用户ID: {}, 用户名: {}", 
                httpRequest.getMethod(), 
                httpRequest.getRequestURI(), 
                userId != null ? userId : "匿名",
                username != null ? username : "匿名");
        
        chain.doFilter(request, response);
    }
}